import { Space, Table, Tag, Modal, Button, Input, Popconfirm } from 'antd'
import React from 'react'
import { GoodsModal } from './GoodsModal'
import {
    getGoodsList,
    addOneGoods,
    deleteOneGoods,
    deleteGoodsByKeys,
    getGoodsByName,
    updateOneGoods
} from '../../services/goods'
import './Goods.less'
import * as moment from 'moment'
import { TableRowSelection } from 'antd/lib/table/interface'

/** 表头 */
interface IGoodsTableTitle {
    title: string
    dataIndex: string
    key: string
    width?: string
    // render 方法正常会返回 JSX 元素
    render?: (value?: any, record?: any, index?: number) => any
}

/** 物品属性 */
export interface IGoodsProps {
    key: string
    name: string
    num: number
    description: string
    tags: string[]
}

/** Goods 类下的 state 类型 */
interface IGoodsState {
    columns: IGoodsTableTitle[]
    dataSource: IGoodsProps[]
    visible: boolean
    // 弹窗 loading 状态
    confirmLoading: boolean
    choice: string
    showList: IGoodsProps
    selectedRowKeys: string[]
}

export class Goods extends React.Component {
    public state: IGoodsState = {
        columns: [
            {
                title: '物品名称',
                dataIndex: 'name',
                key: 'name'
            },
            {
                title: '数量',
                dataIndex: 'num',
                key: 'num'
            },
            {
                title: '描述',
                dataIndex: 'description',
                key: 'description',
                width: '200px'
            },
            {
                title: '标签',
                dataIndex: 'tags',
                key: 'tags',
                render: (tags: string[]) =>
                    tags.map(tag => {
                        let color = tag.length > 2 ? 'geekblue' : 'green'
                        if (tag === 'loser') {
                            color = 'volcano'
                        }
                        return (
                            <Tag color={color} key={tag}>
                                {tag}
                            </Tag>
                        )
                    })
            },
            {
                title: '最新变动时间',
                dataIndex: 'updatedAt',
                key: 'updatedAt',
                render: (time: string) => {
                    return moment(time).format('YYYY-MM-DD')
                }
            },
            {
                title: '操作',
                dataIndex: 'action',
                key: 'action',
                render: (value: any, item: IGoodsProps) => (
                    <Space size="middle">
                        <a onClick={() => this.onClickShow(item)}>查看</a>
                        <a onClick={() => this.onClickEdit(item)}>编辑</a>
                        <Popconfirm
                            title="确定删除？"
                            okText="确认"
                            cancelText="取消"
                            onConfirm={() => this.onClickDelete(item)}
                        >
                            <a>删除</a>
                        </Popconfirm>
                    </Space>
                )
            }
        ],
        dataSource: [],
        visible: false,
        confirmLoading: false,
        choice: '',
        showList: {
            key: '',
            name: '',
            num: 0,
            description: '',
            tags: []
        }, // 查看列表传的对象
        selectedRowKeys: [] // Check here to configure the default column
    }

    /** 获取组件实例 */
    public goodsModalRef = React.createRef<GoodsModal>()

    public componentDidMount() {
        this.getParams()
    }

    // 获取列表
    public async getParams() {
        const res = await getGoodsList()
        this.setState({
            dataSource: res
        })
    }

    // 查看
    public onClickShow(item: IGoodsProps) {
        console.log('[Goods] onClickShow', item)
        this.setState({
            visible: true,
            choice: 'show',
            showList: item
        })
    }

    // 编辑
    public onClickEdit(item: IGoodsProps) {
        console.log('[Goods] onClickEdit', item)
        this.setState({
            visible: true,
            choice: 'edit',
            showList: item
        })
    }

    // 删除
    public onClickDelete = async (item: IGoodsProps) => {
        console.log('[Goods] onClickDelete', item)
        this.setState({
            choice: 'delete'
        })
        await deleteOneGoods(item.key)
        this.getParams()
    }

    // 添加
    public onClickAdd() {
        this.setState({
            visible: true,
            choice: 'add'
        })
    }

    // 批量删除
    public onClickBatchDelete = async () => {
        console.log('批量删除')
        this.setState({
            choice: 'batchDelete'
        })
        await deleteGoodsByKeys(this.state.selectedRowKeys)
        this.getParams()
    }

    // 搜索
    public onSearch = async (e: string) => {
        console.log('搜索', e)
        this.setState({
            choice: 'search'
        })
        const res = await getGoodsByName(e)
        this.setState({
            dataSource: res
        })
    }

    // 弹框确认
    public handleOk = async (e: React.MouseEvent) => {
        const { choice } = this.state
        // 开始等待提交接口返回
        const formData = this.goodsModalRef.current!.getAllFormData()
        console.log('[Goods] handleOk', formData)
        this.setState({
            confirmLoading: true
        })
        if (choice === 'add') {
            await addOneGoods(formData as IGoodsProps)
        } else if (choice === 'edit') {
            await updateOneGoods(formData as IGoodsProps)
        }
        this.setState({
            confirmLoading: false,
            visible: false
        })
        this.getParams()
        this.goodsModalRef.current!.reset()
    }

    // 弹框取消
    public handleCancel = (e: React.MouseEvent) => {
        this.setState({
            confirmLoading: false,
            visible: false
        })
        this.goodsModalRef.current!.reset()
    }

    // 改变选择表格项
    public onSelectChange = (selectedRowKeys: React.Key[]) => {
        console.log('selectedRowKeys changed: ', selectedRowKeys)
        this.setState({ selectedRowKeys })
    }

    public render() {
        const { dataSource, columns, visible, confirmLoading, showList, choice, selectedRowKeys } =
            this.state
        const { Search } = Input
        const rowSelection: TableRowSelection<IGoodsProps> = {
            selectedRowKeys,
            onChange: this.onSelectChange
        }
        return (
            <div className="goods-page">
                <div className="goods-operation">
                    <Search
                        className="goods-search"
                        placeholder="input name"
                        onSearch={(e: string) => this.onSearch(e)}
                        enterButton
                    />
                    <Popconfirm
                        placement="bottom"
                        title="确定批量删除？"
                        onConfirm={() => this.onClickBatchDelete()}
                        okText="确认"
                        cancelText="取消"
                    >
                        <Button type="primary" className="addButton">
                            批量删除
                        </Button>
                    </Popconfirm>
                    <Button type="primary" onClick={() => this.onClickAdd()} className="addButton">
                        添加物品
                    </Button>
                </div>
                <Table rowSelection={rowSelection} dataSource={dataSource} columns={columns} />
                <Modal
                    title="查看物品详情"
                    visible={visible}
                    onOk={this.handleOk}
                    confirmLoading={confirmLoading}
                    onCancel={this.handleCancel}
                >
                    <GoodsModal ref={this.goodsModalRef} showList={showList} choice={choice} />
                </Modal>
            </div>
        )
    }
}
